import { defineStore } from 'pinia'
import type { Ref } from 'vue'
import { ref } from 'vue'
import { emitter } from '@/emitter/emitter'

export const useUserStore = defineStore(
  'admin-user',
  () => {
    const token: Ref<string> = ref('')
    const setToken = (newToken: string): void => {
      token.value = newToken
    }
    const removeToken = (): void => {
      token.value = ''
    }
    const isLogin = (): boolean => {
      return !!token.value
    }
    const userInfo: Ref<Store.User.UserInfo> = ref({
      id: 0,
      username: '',
      nickname: '',
      password: '',
      email: '',
      gender: 0,
      avatar: '',
      desc: '',
      isAdmin: false
    })

    const setUserInfo = (info: Store.User.UserInfo): void => {
      userInfo.value = info
    }
    const isAdmin = (): boolean => {
      return userInfo.value.isAdmin
    }
    const cleatUserInfo = (): void => {
      userInfo.value = {
        id: 0,
        username: '',
        nickname: '',
        password: '',
        email: '',
        gender: 0,
        avatar: '',
        desc: '',
        isAdmin: false
      }
    }
    const logout = (): void => {
      removeToken()
      cleatUserInfo()
      emitter.emit('USER:LOGOUT')
    }

    return {
      token,
      setToken,
      removeToken,
      isLogin,
      userInfo,
      setUserInfo,
      isAdmin,
      cleatUserInfo,
      logout
    }
  },
  {
    persist: true
  }
)
//注册一个事件监听，当接收到API:UN_AUTH事件时，调用useUserStore().removeToken()方法
emitter.on('API:UN_AUTH', () => {
  useUserStore().removeToken()
})
